<!DOCTYPE html>
<html lang="zh_CN">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>文章内容</title>
    <link rel="stylesheet" href="${ctxPath}/assets/libs/layui-2.7.6/css/layui.css"/>
    <link rel="stylesheet" href="${ctxPath}/assets/module/admin.css">
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
        body .tox-tinymce-aux {
            z-index: 19892000;
        }
    </style>
</head>
<body>
<!-- 正文开始 -->
<div class="layui-container" style="width:90%;">
    <form id="addOrUpdateForm" class="layui-form model-form" lay-filter="addOrUpdateForm">
        <div class="layui-row layui-col-space10">
            <div class="layui-col-md8">
                <div class="layui-panel" style="padding: 20px;">
                    <div class="layui-form-item">
                        <label class="layui-form-label layui-form-required">标题</label>
                        <div class="layui-input-block">
                            <input name="title" class="layui-input" placeholder="请输入标题"
                                   lay-verType="tips"
                                   lay-verify="required" required/>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-col-md4">
                <div class="layui-panel" style="padding: 20px;">
                    <div class="layui-form-item">
                        <label class="layui-form-label layui-form-required">发布状态</label>
                        <div class="layui-input-block">
                            <!--                                        <div id="releaseType" style="width: 184px"></div>-->
                            <input id="releaseType" type="checkbox" name="releaseType" lay-skin="switch"
                                   lay-filter="releaseType" lay-text="已发布|下架" >
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-row layui-col-space10">
            <div class="layui-col-xs4 layui-col-sm7 layui-col-md8">
                <div class="layui-panel" style="padding: 15px;">
                    <input name="id" type="hidden"/>
                    <input name="articleId" type="hidden"/>
                    <div class="layui-form-item">
                        <label class="layui-form-label layui-form-required">内容</label>
                        <div class="layui-input-block">
                            <textarea name="content" id="contentEditor" placeholder="请输入文章内容"
                                      class="layui-textarea"></textarea>
                        </div>
                    </div>
                    <div class="layui-form-item text-right">
                        <button class="layui-btn layui-btn-primary" type="button" id="formBackBtn">取消</button>
                        <!--          <button class="layui-btn layui-btn-warm" lay-filter="formSaveBtn" lay-submit>暂存</button>-->
                        <button class="layui-btn" lay-filter="formSubmitBtn" lay-submit>保存</button>
                    </div>
                </div>
            </div>
            <div class="layui-col-xs4 layui-col-sm5 layui-col-md4">
                <div class="layui-panel" style="padding: 15px;">
                    <div class="layui-form-item">
                        <label class="layui-form-label layui-form-required">封面图片</label>
                        <div class="layui-input-block">
                            <div class="layui-upload-drag" id="imageSrc">
                                <i class="layui-icon"></i>
                                <p>点击上传，或将图片拖拽到此处</p>
                                <div class="layui-hide" id="uploadView">
                                    <hr>
                                    <img src="" alt="上传成功后渲染" style="max-width: 150px">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label layui-form-required">分类</label>
                            <div class="layui-input-block">
                                <div id="catalogSelectBox" class="ew-xmselect-tree" style="width: 184px"></div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label layui-form-required">关键词</label>
                            <div class="layui-input-block">
                                <input name="keywords" class="layui-input" placeholder="请输入关键词"
                                       lay-verType="tips" lay-verify="required" required/>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label layui-form-required">标签</label>
                            <div class="layui-input-block">
                                <input name="tags" class="layui-input" placeholder="请输入标签" lay-verType="tips"
                                       lay-verify="required" required/>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label layui-form-required">摘要</label>
                            <div class="layui-input-block">
                                <textarea name="description" class="layui-textarea"
                                          placeholder="请输入摘要"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label layui-form-required">发布时间</label>
                            <div class="layui-input-block">
                                <input type="text" name="publishTime" id="publishTime" lay-verify="date"
                                       placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label layui-form-required">序号</label>
                            <div class="layui-input-block">
                                <input name="orderNum" class="layui-input" placeholder="请输入序号"
                                       lay-verType="tips" lay-verify="required" required/>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label layui-form-required">置顶</label>
                            <div class="layui-input-block">
                                <div id="isTop" style="width: 184px"></div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label layui-form-required">热点</label>
                            <div class="layui-input-block">
                                <div id="isHot" style="width: 184px;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<!-- 加载动画 -->
<div class="page-loading">
    <div class="ball-loader">
        <span></span><span></span><span></span><span></span>
    </div>
</div>
<!-- js部分 -->
<script src="${ctxPath}/assets/libs/layui-2.7.6/layui.js"></script>
<script src="${ctxPath}/assets/js/common.js"></script>
<script src="${ctxPath}/assets/libs/tinymce/tinymce.min.js"></script>
<script src="${ctxPath}/assets/libs/tinymce/jquery.tinymce.min.js"></script>
<script>
    layui.use(['layer', 'table', 'tableX', 'notice', 'xnUtil', 'transfer', 'xmSelect', 'laydate', 'upload', 'form'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var admin = layui.admin;
        var form = layui.form;
        var xnUtil = layui.xnUtil;
        var xmSelect = layui.xmSelect;
        var laydate = layui.laydate;
        var upload = layui.upload;

        var imageUrl;

        laydate.render({
            elem: '#publishTime'
        });

        var articleId = admin.getTempData('articleId');

        var source = admin.getTempData("source");

        var articleContentId = null;

        var articleContent = null;

        var editData = admin.getTempData("editData");
        ;

        layer.ready(function () {
            //通过articleId 获取文章内容信息
            admin.req(getProjectUrl() + 'getContentByArticleId/' + articleId, function (res) {
                if (res.data != null) {
                    articleContentId = res.data.id;
                    articleContent = res.data.content;
                }
            }, 'get')

            if (editData != null) {
                //alert(JSON.stringify(editData));
                layui.$('#uploadView').removeClass('layui-hide').find('img').attr('src', getProjectUrl() + editData.imageSrc);
                if (editData.status == '1') {
                    $("#releaseType").attr("checked", "checked");
                } else {
                    $("#releaseType").removeAttr('checked');
                }
                form.val('addOrUpdateForm', editData);
            }

        })

        const image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open('POST', getProjectUrl() + 'sysFileInfo/minio/upload');

            xhr.upload.onprogress = (e) => {
                progress(e.loaded / e.total * 100);
            };

            xhr.onload = () => {
                var res = JSON.parse(xhr.responseText);
                /* {"success":true,"code":200,"message":"请求成功","data":"1609045157607628802","dir":"/","msg":"请求成功"} */
                if (!res.success) {
                    layui.notice.msg(res.message, {icon: 2});
                    return false;
                } else {
                    resolve(getProjectUrl() + 'sysFileInfo/minio/preview?id=' + res.data);
                }
            };

            xhr.onerror = () => {
                reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
            };

            const formData = new FormData();
            formData.append('file', blobInfo.blob(), blobInfo.filename());

            xhr.send(formData);
        });

        // 渲染富文本编辑器
        tinymce.init({
            selector: '#contentEditor',
            height: 525,
            branding: false,
            language: 'zh_CN',
            plugins: 'autoresize code print preview fullscreen searchreplace save autosave link autolink image media table codesample lists advlist hr charmap emoticons anchor directionality pagebreak quickbars nonbreaking visualblocks visualchars wordcount',
            toolbar: 'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
                     styleselect blocks fontfamily fontsize | bullist numlist | blockquote subscript superscript removeformat | \
                     table image media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | bdmap indent2em lineheight formatpainter axupimgs',
            font_family_formats: "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
            toolbar_mode: 'wrap',
            promotion: false,
            placeholder: '在这里输入正文内容',
            content_style: "img {max-width:100%;}",
            file_picker_types: 'media',
            relative_urls: false,
            remove_script_host: false,
            document_base_url: getProjectUrl(),
            images_upload_handler: image_upload_handler,
            init_instance_callback: function (editor) {
                if (articleContent != null) {
                    tinymce.get('contentEditor').setContent(articleContent);
                }
                admin.removeLoading();
            }
        });



        /* 返回按钮点击事件 */
        $('#formBackBtn').click(function () {
            if (source === 'article') {
                window.location.href = getProjectUrl() + 'article/index';
            }
            if (source === 'page') {
                window.location.href = getProjectUrl() + 'page/index';
            }
            if (source === 'product') {
                window.location.href = getProjectUrl() + 'product/index';
            }
        });

        // 表单暂存事件
        // form.on('submit(formSaveBtn)', function (data) {
        //   var content = tinymce.get('contentEditor').getContent();
        //   layer.load(2);
        //   var url = articleId ? getProjectUrl() + '/articleContent/edit' : getProjectUrl() + '/articleContent/add';
        //   data.field.status = 0;
        //   data.field.content = content;
        //   admin.req(url, JSON.stringify(data.field), function(res){
        //     layer.msg(res.message, {icon: 1, time: 1000}, function () {
        //       window.location.href = getProjectUrl() + 'article/index';
        //       return false;
        //     });
        //   }, 'post');
        //   return false;
        // });

        /**
         * 渲染字典
         * */
        var isTop = xmSelect.render({
            el: '#isTop',
            name: 'isTop',
            data: xnUtil.getDictDataByDictTypeCode('yes_or_no', null),
            layVerify: 'required',
            layVerType: 'tips',
            radio: true,
            initValue: editData ? [editData.isTop] : [],
            clickClose: true,
            model: {icon: 'hidden', label: {type: 'text'}},
            prop: {
                name: 'name',
                value: 'code'
            },
            tips: '请选择是否置顶'
        });

        /**
         * 渲染字典
         * */
        var isHot = xmSelect.render({
            el: '#isHot',
            name: 'isHot',
            data: xnUtil.getDictDataByDictTypeCode('yes_or_no', null),
            layVerify: 'required',
            layVerType: 'tips',
            initValue: editData ? [editData.isHot] : [],
            radio: true,
            clickClose: true,
            model: {icon: 'hidden', label: {type: 'text'}},
            prop: {
                name: 'name',
                value: 'code'
            },
            tips: '请选择是否热点'
        });

        admin.req(getProjectUrl() + 'catalog/tree', function (res) {
            // 渲染下拉树
            xmSelect.render({
                el: '#catalogSelectBox',
                name: 'catalogId',
                height: '250px',
                layVerify: 'required',
                layVerType: 'tips',
                data: xnUtil.handleZtreeDataRootNode(res.data),
                initValue: editData ? [editData.catalogId] : [],
                model: {label: {type: 'text'}},
                prop: {
                    name: 'title',
                    value: 'id'
                },
                radio: true,
                clickClose: true,
                tree: {
                    show: true,
                    indent: 15,
                    strict: false,
                    expandedKeys: true
                },
                tips: '请选择上级栏目'
            });
        }, {async: false});

        //拖拽上传
        upload.render({
            elem: '#imageSrc'
            , field: "file"
            , url: getProjectUrl() + 'sysFileInfo/minio/upload'
            , accept: 'images'
            , done: function (res) {
                layer.msg('上传成功');
                layui.$('#uploadView').removeClass('layui-hide').find('img').attr('src', getProjectUrl() + 'sysFileInfo/minio/preview?id=' + res.data);
                imageUrl = 'sysFileInfo/minio/preview?id=' + res.data;
                console.log(res)
            }
        });

        //监听开关事件
        form.on('switch(releaseType)', function (data) {
            if(articleId == null){
                return false;
            }
            var status = $("#releaseType ").is(':checked') === true ? '1' : '2';
            var url = null;
            if (source === 'article') {
                url =getProjectUrl() + 'releaseArticle';
            }
            if (source === 'page') {
                url =getProjectUrl() + 'releasePage';
            }
            if (source === 'product') {
                url =getProjectUrl() + 'releaseProduct';
            }

            admin.req(url, {"id":articleId,"status":status}, function (res) {
                editData.status = status;
                if(status === '1'){
                    layer.msg("发布成功",{icon: 1, time: 1000},function (){
                        if (source === 'article') {
                            window.location.href = getProjectUrl() + 'article/index';
                        }
                        if (source === 'page') {
                            window.location.href = getProjectUrl() + 'page/index';
                        }
                        if (source === 'product') {
                            window.location.href = getProjectUrl() + 'product/index';
                        }
                    });
                }else{
                    layer.msg("下架成功",{icon: 1, time: 1000},function (){
                        if (source === 'article') {
                            window.location.href = getProjectUrl() + 'article/index';
                        }
                        if (source === 'page') {
                            window.location.href = getProjectUrl() + 'page/index';
                        }
                        if (source === 'product') {
                            window.location.href = getProjectUrl() + 'product/index';
                        }
                    });
                }
            }, 'post');
            return false;
        });

        // 表单提交事件
        form.on('submit(formSubmitBtn)', function (data) {
            var content = tinymce.get('contentEditor').getContent();
            if (content === null || content === undefined || content === '') {
                layui.notice.msg('文章内容不能为空', {icon: 2});
                return false;
            }
            layer.load(2);
            var url = null;
            if (source === 'article') {
                url = articleId ? getProjectUrl() + 'article/edit' : getProjectUrl() + 'article/add';
            }
            if (source === 'page') {
                url = articleId ? getProjectUrl() + 'page/edit' : getProjectUrl() + 'page/add';
            }
            if (source === 'product') {
                url = articleId ? getProjectUrl() + 'product/edit' : getProjectUrl() + 'product/add';
            }
            //data.field.articleId = articleId;
            data.field.content = content;
            data.field.id = articleId;
            data.field.status = $("#releaseType ").is(':checked') == true ? '1' : '2';
            data.field.imageSrc = editData ? (imageUrl ? imageUrl : editData.imageSrc) : imageUrl;
            if (source === 'article') {
                data.field.type = 1;
            }
            if (source === 'page') {
                data.field.type = 2;
            }
            if (source === 'product') {
                data.field.type = 3;
            }
            admin.req(url, JSON.stringify(data.field), function (res) {
                layer.msg(res.message, {icon: 1, time: 1000}, function () {
                    tinymce.get('contentEditor').isNotDirty = 1;
                    if (source === 'article') {
                        window.location.href = getProjectUrl() + 'article/index';
                    }
                    if (source === 'page') {
                        window.location.href = getProjectUrl() + 'page/index';
                    }
                    if (source === 'product') {
                        window.location.href = getProjectUrl() + 'product/index';
                    }
                    return false;
                });
            }, 'post');
            return false;
        });
    });
</script>
</body>
</html>